﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using Elmah;
using Viettel.VOFFICE.DAO.Enums;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    [AttributeHelper("BookController_ControllerName")]
    public class BookController : BaseController
    {
        /// <summary>
        /// lấy toàn bộ sổ văn bản, với các thông tin phân trang
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionName("get_all_books")]
        [AttributeHelper("BookController_GetAllData")]
        public JsonResult GetAll(int pageIndex = 0, int pageSize = 0)
        {
            //có phân trang
            try
            {
                if (pageSize > 0 && pageIndex >= 0)
                {
                    var list = unitOfWork.BookRepository.GetWithPaging(pageIndex, pageSize);
                    return Json(new JsonResponse()
                                    {

                                        Status = true,
                                        Result = new
                                                     {
                                                         PageIndex = list.PageIndex,
                                                         PageSize = list.PageSize,
                                                         PageCount = list.PageCount,
                                                         List = list.Select(o => new BookModel(o))
                                                     }
                                    }, JsonRequestBehavior.AllowGet);
                }
                //không phân trang
                else
                {

                    var list = unitOfWork.BookRepository.Get().Select(o => new BookModel(o));
                    return Json(new JsonResponse() { Status = true, Result = list }, JsonRequestBehavior.AllowGet);
                } //end if
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(new NotSupportedException("", ex));
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                throw;
            }//end try
        }

        /// <summary>
        /// Cập nhập sổ văn bản
        /// </summary>
        /// <param name="book"></param>
        /// <param name="modified"> </param>
        /// <returns></returns>
        [HttpPut]
        [ActionName("update_book")]
        [AttributeHelper("BookController_UpdateBook")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateBook(BookModel book, string modified = "all")
        {
            try
            {
                List<ValidationResult> outError;
                if (book.IsValid(out outError))
                {
                    var dbBook = unitOfWork.BookRepository.GetById(book.Id);
                    if (dbBook == null)
                    {
                        return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = Resources.Resources.ManageBookBookNotFound
                        });
                    }
                    if (modified.ToUpper().Contains("ISACTIVE"))
                    {
                        dbBook.IsActive = book.IsActive;
                    }
                    else if (modified.ToUpper().Contains("ISDEFAULT"))
                    {
                        dbBook.IsDefault = book.IsDefault;
                    }
                    else//cập nhập hết
                    {
                        dbBook.Name = book.Name;
                        dbBook.Description = book.Description;
                        dbBook.BookType = book.BookType;
                        dbBook.CurrentNumber = book.CurrentNumber;
                        dbBook.Sequence = book.Sequence;
                        dbBook.IsActive = book.IsActive;
                        dbBook.IsDefault = book.IsDefault;
                        dbBook.Format = book.Format != null && !book.Format.ToLower().Contains("#n#") ? (book.Format + "#n#") : book.Format;
                        dbBook.ResetBy = book.ResetBy;
                        dbBook.OfficeIdUse = book.OfficeIdUse;
                    }//end if
                    dbBook.UpdatedAt = DateTime.Now;
                    unitOfWork.BookRepository.Update(dbBook);
                    return Json(SimplyResponse.Response200());
                }
                else
                {
                    return Json(new JsonResponse()
                                 {
                                     Status = false,
                                     Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                                 });
                }//end ìf
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }

        [HttpPost]
        [ActionName("add_book")]
        [AttributeHelper("BookController_CreateBook")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddBook(BookModel book)
        {
            try
            {
                try
                {
                    List<ValidationResult> outError;
                    if (book.IsValid(out outError))
                    {
                        var dbBook = new Book
                                         {
                                             //Id = book.Id,
                                             Name = book.Name,
                                             Description = book.Description,
                                             BookType = book.BookType,
                                             CurrentNumber = book.CurrentNumber,
                                             Sequence = book.Sequence,
                                             IsActive = book.IsActive,
                                             IsDefault = book.IsDefault,
                                             Format = book.Format != null && !book.Format.ToLower().Contains("#n#") ? (book.Format + "#n#") : book.Format,
                                             ResetBy = book.ResetBy,
                                             OfficeIdUse = book.OfficeIdUse,
                                             CreatedAt = DateTime.Now,
                                             UpdatedAt = DateTime.Now
                                         };
                        unitOfWork.BookRepository.Insert(dbBook);
                        return Json(SimplyResponse.ResposeWithId(dbBook.Id));
                    }
                    else
                    {
                        return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                        });
                    }//end ìf
                }
                catch (Exception)
                {
                    return Json(SimplyResponse.Response500());
                    //throw;
                }
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }

        /// <summary>
        /// Xóa sổ văn bản, trong trường hợp có ràng buộc thì để nguyên không xóa nữa
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("delete_book")]
        [AttributeHelper("BookController_DeleteBook")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult DeleteBook(int id)
        {
            try
            {
                unitOfWork.BookRepository.Delete(id);
                return Json(SimplyResponse.Response200());
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }

        /// <summary>
        /// Tìm kiếm sổ văn bản
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("search_book")]
        [AttributeHelper("BookController_SearchBook")]
        public JsonResult Search(string key)
        {
            try
            {
                var items = unitOfWork.BookRepository.Search(key);
                return Json(new JsonResponse() { Status = true, Result = items.Select(o => new BookModel(o)) },
                            JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                //throw;
            }
        }

        /// <summary>
        /// Hàm lấy giá tri: số vào sổ và gen mã hồ sơ khi vào sổ văn bản
        /// </summary>
        /// <param name="bookId"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("get_new_number")]
        public JsonResult GetNewNumber(int bookId)
        {
            try
            {
                var book = unitOfWork.BookRepository.GetById(bookId);
                if (book == null || book.IsActive == false)
                {
                    return Json(new JsonResponse() { Status = false, Result = @Resources.Resources.ManageBookBookNotFound }, JsonRequestBehavior.AllowGet);
                }
                var number = book.DocumentBooks.Count() + 1;
                var format = string.Empty;
                if (!string.IsNullOrWhiteSpace(book.Format))
                {
                    switch (book.ResetBy)
                    {
                        case (int)BookResetType.None:
                            format = UtilityHelper.MakeDocCode(book.Format, number);
                            break;
                        case (int)BookResetType.ByMonth:
                            var totalByMonth = unitOfWork.DocumentBookRepository.CountByGreaterCreatedAt(UtilityHelper.StartDayOfMonth());
                            format = UtilityHelper.MakeDocCode(book.Format, totalByMonth + 1);
                            break;
                        case (int)BookResetType.ByQuarter:
                            var totalByQuarter = unitOfWork.DocumentBookRepository.CountByGreaterCreatedAt(UtilityHelper.StartDayOfQuarter());
                            format = UtilityHelper.MakeDocCode(book.Format, totalByQuarter + 1);
                            break;
                        case (int)BookResetType.ByYear:
                            var totalByYear = unitOfWork.DocumentBookRepository.CountByGreaterCreatedAt(UtilityHelper.StartDayOfYear());
                            format = UtilityHelper.MakeDocCode(book.Format, totalByYear + 1);
                            break;
                    }
                }
                return Json(new JsonResponse() { Status = true, Result = new { Code = format, Number = number } }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
            }
        }
    }
}
